package com.xmqian.app.project.ui.common.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.DownloadListener
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.coszero.common.base.mvp.BaseMvpFragment
import com.coszero.ui.dialog.AlertDialog
import com.coszero.ui.dialog.ToastUtils
import com.coszero.utils.device.DeviceNetStateUtils
import com.coszero.utils.utils.LogX
import com.example.xmqian.databinding.FragmentMyWebViewBinding
import com.xmqian.app.project.ui.common.contract.MyWebViewContract
import com.xmqian.app.project.ui.common.model.MyWebViewModel
import com.xmqian.app.project.ui.common.presenter.MyWebViewPresenter
import org.json.JSONException
import org.json.JSONObject

/**
 * Desc： 展示网页界面
 *
 *
 * Author： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/9/12 17:50
 */
class MyWebViewFragment : BaseMvpFragment<MyWebViewPresenter?>(), MyWebViewContract.View {
    //当前打开的type类型，-1 为默认类型，表示仅打开url/文本
    private var mCurrentType = -1

    var mWebView: WebView? = null

    var mUrl: String? = null
    var mTitle: String? = null

    private var pageId = 0
    private var mTitleCallBack: TitleCallBack? = null
    private var binding: FragmentMyWebViewBinding? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is TitleCallBack) {
            mTitleCallBack = context
        } else {
            Throwable("no implement TitleCallBack")
        }
    }

    @SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
    @Suppress("deprecation")
    override fun initView() {
        mWebView = binding!!.pwvWeb
        //获取intent里的值并设置标题
        val data = arguments
        mUrl = data!!.getString(EXTRA_TEXT)
        mTitle = data.getString(EXTRA_TITLE)
        mCurrentType = data.getInt(EXTRA_TYPE, -1)
        mTitleCallBack!!.setTitleListenner(mTitle)

        //WebView 配置相关
        mWebView.getSettings().javaScriptEnabled = true
        mWebView.addJavascriptInterface(InJavaScriptLocalObj(), "java_obj")
        mWebView.getSettings().defaultTextEncodingName = "utf-8"
        mWebView.getSettings().loadsImagesAutomatically = true
        mWebView.getSettings().allowFileAccess = true
        mWebView.getSettings().javaScriptEnabled = true
        mWebView.getSettings().javaScriptCanOpenWindowsAutomatically = true
        mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH)
        if (DeviceNetStateUtils.isNetWorkAvailble(activity)) {
            mWebView.getSettings().cacheMode = WebSettings.LOAD_NO_CACHE
        } else {
            mWebView.getSettings().cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().mixedContentMode =
                WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        mWebView.getSettings().allowContentAccess = true
        mWebView.getSettings().databaseEnabled = true
        mWebView.getSettings().domStorageEnabled = true
        //        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().savePassword = false
        mWebView.getSettings().saveFormData = false

        mWebView.setDownloadListener(DownloadListener { url: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long ->
            // 监听下载功能，当用户点击下载链接的时候，直接调用系统的浏览器来下载
            val uri = Uri.parse(url)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        })

        mWebView.setWebViewClient(MyWebViewClient())

        //自定义控件已设置
//        mWebView.setWebChromeClient(new WebChromeClient());
        if (mCurrentType == TYPE_SINGLE_PAGE) {
            pageId = arguments!!.getInt(EXTRA_PAGE_ID, 0)
            presenter.getSinglePage(pageId)
            return
        }

        //特殊
        if (mCurrentType == HELP_FEEDBACK) {
            pageId = arguments!!.getInt(EXTRA_PAGE_ID, 0)
            presenter.getFeedBackInfo(pageId)
            return
        }

        //如果以http为起始，说明是url地址，否则作为文本打开内容
        if (mUrl!!.startsWith("http")) {
            mWebView.getSettings().useWideViewPort = true
            mWebView.getSettings().loadWithOverviewMode = true
            mWebView.loadUrl(mUrl!!)
        } else {
            loadHtmlContent(mUrl)
        }
    }

    private fun loadHtmlContent(content: String?) {
        mWebView!!.loadDataWithBaseURL(
            null,
            getHtmlData(content),
            "text/html;charset=UTF-8",
            null,
            null
        )
    }

    private fun getHtmlData(bodyHTML: String?): String {
        val head = "<head><style>img{max-width: 100%; width:auto; height: auto;}</style></head>"
        return "<html>$head<body>$bodyHTML</body><html>"
    }

    override fun initData() {
    }

    override fun lazyLoadData() {
    }

    override fun getLayoutView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        attachToParent: Boolean
    ): View {
        binding = FragmentMyWebViewBinding.inflate(inflater, container, attachToParent)
        return binding!!.root
    }

    override fun onNetworkError() {
    }

    override fun onGetSinglePageSucceed(pageBean: MyWebViewModel) {
        setTitle(pageBean.title)
        loadHtmlContent(pageBean.contents)
    }

    override fun onRequestFailed(message: String?) {
        ToastUtils.showMsg(message)
    }

    override fun getPresenter(): MyWebViewPresenter {
        return MyWebViewPresenter(this)
    }

    /**
     * 逻辑处理
     */
    internal inner class InJavaScriptLocalObj {
        @JavascriptInterface
        fun getSource(html: String) {
            var html = html
            LogX.i(html)
            try {
                html = html.substring(html.indexOf("{"), html.lastIndexOf("}") + 1)
                val result = JSONObject(html)

                if (result.optInt("result") == 1) {
                    //如果是银行卡还款/支付结果成功了，跳转到订单状态页面
                    if (mCurrentType == TYPE_BANK_PAYMENT) {
//                        startActivity(new Intent(MyWebViewFragment.this, OrderSucceedActivity.class));
//                        MyWebViewFragment.this.finish();
                        return
                    }
                }
                showResult(result.optString("message"))
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
    }

    private fun showResult(message: String) {
        val dialog = AlertDialog(activity)
        dialog.builder().setTitle("提示").setMsg(message)

        dialog.setCancelable(false)
        dialog.show()
    }


    private inner class MyWebViewClient : WebViewClient() {
        @Suppress("deprecation")
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            LogX.e(url)
            if (url.contains("BackSuccess?type=1")) {
//                mPresenter.mobilezr2();
            }
            return super.shouldOverrideUrlLoading(view, url)
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            if (mCurrentType == -1) return
            if (mCurrentType == TYPE_BANK_CERT || mCurrentType == TYPE_MOBILE_CERT || mCurrentType == TYPE_BANK_PAYMENT) {
                view.loadUrl("javascript:window.java_obj.getSource(document.getElementsByTagName('body')[0].innerHTML);")
            }
        }
    }

    /**
     * 网页返回
     */
    fun onBackPressed(): Boolean {
        if (mWebView!!.canGoBack()) {
            mWebView!!.goBack()
            return true
        }
        return false
    }

    interface TitleCallBack {
        fun setTitleListenner(title: String?)
    }

    companion object {
        //因接口地址不同，特殊处理
        const val HELP_FEEDBACK: Int = 0x56

        private const val EXTRA_TYPE = "mCurrentType"
        private const val EXTRA_PAGE_ID = "pageId"
        private const val EXTRA_TEXT = "text"
        private const val EXTRA_TITLE = "title"

        //认证相关type，需要检测服务器返回的 json 字符串
        const val TYPE_BANK_CERT: Int = 0x11
        const val TYPE_MOBILE_CERT: Int = 0x22

        //银行支付type，需要检测服务器返回的 json 字符串
        const val TYPE_BANK_PAYMENT: Int = 0x33

        const val TYPE_SINGLE_PAGE: Int = 0x44

        /**
         * @param type 类型
         * @param pageId 网页请求id
         * @param title 标题
         * @param text 内容，有可能是链接地址，有可能是网页内容
         * @return
         */
        fun newInstance(type: Int, pageId: Int, title: String?, text: String?): MyWebViewFragment {
            val args = Bundle()
            args.putInt(EXTRA_TYPE, type)
            args.putInt(EXTRA_PAGE_ID, pageId)
            args.putString(EXTRA_TITLE, title)
            args.putString(EXTRA_TEXT, text)
            val fragment = MyWebViewFragment()
            fragment.arguments = args
            return fragment
        }
    }
}
